package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC1011 {


    public int shipWithinDays(int[] weights, int D) {
        int ub = getSum(weights), lb = getMax(weights), mid = 1;
        while (lb <= ub) {
            mid = lb + (ub - lb) / 2;//in case of integer overflow
            if (canFinish(weights, D, mid)) {
                ub = mid - 1;
            } else {
                lb = mid + 1;
            }
        }

        return lb;
    }

    // 如果载重为 cap，是否能在 D 天内运完货物？
    boolean canFinish(int[] w, int D, int cap) {
        int i = 0;
        for (int day = 0; day < D; day++) {
            int maxCap = cap;
            while ((maxCap -= w[i]) >= 0) {
                i++;
                if (i == w.length)
                    return true;
            }
        }
        return false;
    }

    int getMax(int[] piles) {
        int max = 0;
        for (int n : piles)
            max = Math.max(n, max);
        return max;
    }

    int getSum(int[] arr) {
        int sum = 0;
        for (int el : arr) {
            sum += el;
        }
        return sum;
    }

    public static void main(String[] args) {
        LC1011 an = new LC1011();
        int[] arr = InputUtil.toIntegerArray(" [1,2,3,4,5,6,7,8,9,10]");
        System.out.println(an.shipWithinDays(arr, 5));
    }
}
